<?php
/**
 * Created by PhpStorm.
 * User: George
 * Date: 2017/9/25
 * Time: 11:06
 */

namespace AdminBundle\Task;

/**
 * 响应包体格式
 *  {"code":0,"msg":"ok","time":1479444371,"data":{"id":2,"sentence":"测试仪"}
 * 熟人好友聊天
 * Class ChatToContactTask
 * @package AdminBundle\Task
 */
class ChatToContactTask extends Task
{
    const SOURCE_TYPE_FRIEND = 1; //熟人好友

    /**
     * 返回
     * @return null
     */
    public function jsonTask()
    {
        $data = [
            'app' => 'api', 'os' => 'ios', 'deviceid' => $this->task->getDeviceName(),
            'data' =>
                [
                    'token' => $this->task->getAction(),
                    'mobile' => $this->task->getWebchatUsername(),
                    'webchat' => [$this->task->getWebchatUsername(), $this->task->getNote()]
                ]
        ];

        $url = 'http://admin.bjtwtx.com/api/partner/talk';

        // 获取联系人
        $user_id = $this->task->getMethod();
        $contacts = $this->getContacts($user_id, self::SOURCE_TYPE_FRIEND, '');
        if (empty($contacts)) {
            return null;
        }
        $chats = [];
        foreach ($contacts as $contact) {
            $json = $this->httpJson($url, $data);

            if ($json == null && $json['code'] != 0) {
                continue;
            }
            $dialog = $json['data'];
            $sentences = explode(PHP_EOL, $dialog['sentence']);
            $message = [];
            foreach ($sentences as $sentence) {
                $message[] = ['type' => 'text', 'value' => $sentence, 'delay' => 3];
            }
            $chats[] = [
                'nickname' => $contact['userName'],
                'username' => $contact['nickname'],
                'mobile' => $contact['mobile'],
                'message' => $message,
            ];
        }
        return json_encode($chats);
    }

    /**
     * 根据微信号选择熟人好友进行聊天
     * 规则：随机
     * @return array
     */
    private function getContacts($user_id, $source_type, $tags, $count = 5)
    {
        $friends = $this->em->getRepository('AdminBundle:BaseWebchatMember')->contactOfChat($user_id, $source_type, $tags, $count);
        if ($friends == null)
            return [];
        return $friends;
    }
}